package com.bnz.servlet;

import com.alibaba.fastjson.JSON;
import com.bnz.pojo.R;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {
    private StudentService studentService;
    @Override
    public void init() throws ServletException {
        // 1. 得到spring容器
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        // 2. 得到容器里面的javaBean
        studentService = wac.getBean(StudentService.class);
    }

    // 1. 根据请求参数的不同处理请求
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.1 处理响应页面的内容
        resp.setContentType("text/html;charset=utf8");
        // 1.2 得到请求参数cmd
        String cmd = req.getParameter("cmd");
        // 1.3 根据不同的请求参数调用不同方法
        if (StringUtils.isNotBlank(cmd)){
            // 1.3.1 得到所有学生列表
            if ("list".equals(cmd)){
                list(req,resp);
            }
        }
    }

    // 2. 得到所有学生列表
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 2.1 得到所有学生列表
        List<Student> students = studentService.findAll();
        // 2.2 将集合转换为R对象
        R r = R.ok().put("students", students);
        // 2.3 将R对象转换为JSON字符
        String s = JSON.toJSONString(r);
        // 2.4 输出到页面
        resp.getWriter().println(s);
        // 2.5 刷新
        resp.getWriter().flush();
    }
}
